<?php

namespace app\common\service;


use app\common\util\TpImage;
use think\facade\Request;
use think\facade\Validate;
use think\facade\Filesystem;
use think\Image;
use app\common\util\ExcelHelper;
use app\common\model\TechInformationClassification;
use app\common\model\TechAchievements;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;

class FileService extends Service
{
    /**
     * 上传图片
     * 本地运行如果无法写入图片可能是没有给public目录写权限
     *
     * @param string $path 上传路径，默认为'default'
     * @return array 上传后的图片路径
     */
    public function uploadImage($path = 'default')
    {
        // 获取表单上传文件
        $files = request()->file();

        // 验证上传文件格式和大小
        $size = 6 * 1024 * 1024;
        $this->validate($files, Validate::rule(['file' => 'fileSize:' . $size . '|fileExt:jpeg,jpg,png,webp,mp4,gif']));
        $file = request()->file('file');


        $image = TpImage::open($file);
        $floder = "/storage/" . $path . '/' . date("Ymd") . "/";
        //如果文件夹不存在，就创建文件夹
        if (!is_dir(public_path() . $floder)) {
            mkdir(public_path() . $floder, 0777, true);
        }

        $path = $floder . md5($file->getFilename()) . "_" . rand(100, 999) . '.' . $file->getOriginalExtension();

        // 保存上传文件到public目录下的$path目录中
        //            $path = public_path();
        //            print_r($path);
        //$path = Filesystem::disk('public')->putFile($path, $file);
        //var_dump($path);
        $image->thumb(1000, 1000, Image::THUMB_SCALING)->save(public_path() . $path);

        try {
        } catch (\Exception $e) {
            throw $this->warpException($e, '上传图片失败：\n');
        }

        // 获取图片的url地址
        $path = Request::domain() . getVirRootDir() . $path;
        $path = str_replace('\\', '/', $path);

        return [
            'url' => $path, //为了兼容移动端
            'path' => $path
        ];
    }

    /**
     * 上传图片
     * 本地运行如果无法写入图片可能是没有给public目录写权限
     *
     * @param string $path 上传路径，默认为'default'
     * @return array 上传后的图片路径
     */
    public function uploadImages($extPath = 'default')
    {
        // 验证上传文件格式和大小
        $files = request()->file('file');
        foreach ($files as $file) {
            $this->validate(['file' => $file], Validate::rule(['file' => 'fileSize:2048000|fileExt:jpeg,jpg,png,webp,mp4,gif']));
        }
        $filePaths = [];
        foreach ($files as $file) {
            $path = $extPath;
            try {
                // 保存上传文件到public目录下的$path目录中
                $path = Filesystem::disk('public')->putFile($path, $file);
            } catch (\Exception $e) {
                throw $this->warpException($e, '上传图片失败：\n');
            }
            // 获取图片的url地址
            $path = Request::domain() . getVirRootDir() . '/storage/' . $path;
            $path = str_replace('\\', '/', $path);
            $filePaths[] = $path;
        }
        return [
            'paths' => $filePaths
        ];
    }

    const VIDEO_MIME_TYPES = [
        "video/x-msvideo",
        "video/mp4",
        "video/quicktime",
        "video/x-ms-wmv",
        "video/x-matroska",
        "video/x-flv",
        "video/webm",
        "video/3gpp"
    ];

    public function uploadVideo($extPath = 'default')
    {
        $file = request()->file('file');
        if (!in_array($file->getMime(), self::VIDEO_MIME_TYPES)) {
            throw $this->exception('上传文件格式错误');
        }
        try {
            // 保存上传文件到public目录下的$path目录中
            $path = Filesystem::disk('public')->putFile($extPath, $file);
        } catch (\Exception $e) {
            throw $this->warpException($e, '上传图片失败：\n');
        }

        // 获取图片的url地址
        $path = Request::domain() . getVirRootDir() . '/storage/' . $path;
        $path = str_replace('\\', '/', $path);

        return [
            'path' => $path
        ];
    }

    /**
     * 上传附件
     * 本地运行如果无法写入图片可能是没有给public目录写权限
     *
     * @param string $path 上传路径，默认为'default'
     * @return array 上传后的图片路径
     */
    public function uploadAttachment($path = 'default')
    {
        // 获取表单上传文件
        //$files = request()->file();
        $file = request()->file('file');
        //$this->validate($files, Validate::rule(['file' => 'fileExt:pdf,doc,docx']));

        //格式校验
        $ext = $file->getOriginalExtension();
        $extArray = ["jpg", "png", "gif", "jpeg", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf", "txt", "zip", "7z", "rar", "mp4", "wps"];
        if (!in_array($ext, $extArray)) {
            throw $this->exception("该文件格式不允许上传");
        }

        //大小校验
        $originSize = $file->getSize();
        $size = round($originSize / 1024 / 1024);
        if ($size > 10) {
            throw $this->exception("上传文件大小不允许超过10M");
        }

        try {
            // 保存上传文件到public目录下的$path目录中
            $path = Filesystem::disk('public')->putFile($path, $file);
        } catch (\Exception $e) {
            throw $this->warpException($e, '上传附件失败：\n');
        }

        // 获取图片的url地址
        $path = Request::domain() . getVirRootDir() . '/storage/' . $path;
        $path = str_replace('\\', '/', $path);

        return [
            'path' => $path
        ];
    }

    public function uploadVoice($path = 'default')
    {
        // 获取表单上传文件
        $files = request()->file();
        $file = request()->file('file');
        $this->validate($files, Validate::rule(['file' => 'fileExt:wav']));

        try {
            // 保存上传文件到public目录下的$path目录中
            $path = Filesystem::disk('public')->putFile($path, $file);
        } catch (\Exception $e) {
            throw $this->warpException($e, '上传图片失败：\n');
        }

        // 获取图片的url地址
        $path = Request::domain() . getVirRootDir() . '/storage/' . $path;
        $path = str_replace('\\', '/', $path);

        return [
            'path' => $path
        ];
    }


    /**
     * 获取当前网站的域名地址
     *
     * @return string 域名地址
     */
    protected static function get_domain()
    {
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
    }


    /**
     * 导入Excel文件
     */
    public function importExcel($param = [])
    {
        $param = $this->autoMergeParams($param);
        $path = getValueFromArray("path", $param);
        $start = getValueFromArray("start",$param);
        $end = getValueFromArray("end",$param);

        if (!$path) {
            return "路径为空！";
        }

        // $path = "D:\\phpstudy_pro\\WWW\\work\\农业帮扶\\"; //D:\phpstudy_pro\WWW\work\农业帮扶
        // $file = "广东省科学院成果汇编（2023版）(多sheet).xlsx";

        // $obj = ExcelHelper::instance()->miniimportExecl($path . $file);

        $obj = ExcelHelper::instance()->miniimportExecl($path);

        $columnCnt = 0;
        $options = [];

        $classification_id = 0;

        for ($sheet = $start; $sheet < $end; $sheet++) {

            try{
                $currSheet = $obj->getSheet($sheet);
            }
            catch(Exception $e){
                break;
            }

            
            

            if (isset($options['mergeCells'])) {
                /* 读取合并行列 */
                $options['mergeCells'] = $currSheet->getMergeCells();
            }

            if (0 == $columnCnt) {
                /* 取得最大的列号 */
                $columnH = $currSheet->getHighestColumn();
                /* 兼容原逻辑，循环时使用的是小于等于 */
                $columnCnt = Coordinate::columnIndexFromString($columnH);
            }

            /* 获取总行数 */
            $rowCnt = $currSheet->getHighestRow();
            $data   = [];

            /* 读取内容 */
            for ($_row = 1; $_row <= $rowCnt; $_row++) {
                $isNull = true;

                for ($_column = 1; $_column <= $columnCnt; $_column++) {
                    $cellName = Coordinate::stringFromColumnIndex($_column);
                    $cellId   = $cellName . $_row;
                    $cell     = $currSheet->getCell($cellId);

                    if (isset($options['format'])) {
                        /* 获取格式 */
                        $format = $cell->getStyle()->getNumberFormat()->getFormatCode();
                        /* 记录格式 */
                        $options['format'][$_row][$cellName] = $format;
                    }

                    if (isset($options['formula'])) {
                        /* 获取公式，公式均为=号开头数据 */
                        $formula = $currSheet->getCell($cellId)->getValue();

                        if (0 === strpos($formula, '=')) {
                            $options['formula'][$cellName . $_row] = $formula;
                        }
                    }

                    if (isset($format) && 'm/d/yyyy' == $format) {
                        /* 日期格式翻转处理 */
                        $cell->getStyle()->getNumberFormat()->setFormatCode('yyyy/mm/dd');
                    }

                    $data[$_row][$cellName] = trim($currSheet->getCell($cellId)->getFormattedValue());

                    if (!empty($data[$_row][$cellName])) {
                        $isNull = false;
                    }
                }

                /* 判断是否整行数据为空，是的话删除该行数据 */
                if ($isNull) {
                    unset($data[$_row]);
                }
            }

            $newData = [];

            foreach ($data as $d) {
                foreach ($d as $z) {
                    if ($z != "") {
                        $newData[] = $z;
                    }
                }
            }

            // return $newData;
            // return str_replace(" ","",str_replace("\n", "", trim("联 系 方\n\n式")));

            $achievement_name = "";
            // $classification_id = 0;
            $technology_maturity = "";
            $achievement_introduction = "";
            $cooperation_mode = "";
            $contacts = "";
            $contacts_c = "";
            $technology_source = "";
            $phone = "";
            $units_name = "";

            $classification = [
                "电子与信息" => 9,
                "智库与服务" => 7,
                "农业技术" => 6,
                "节能环保" => 5,
                "高端设备与先进制造" => 4,
                "新材料" => 3,
                "生物与健康" => 2,
                "电子信息技术" => 10,
            ];
            
            if($newData[4] == "成果名称"){
                $array = explode('、', $newData[1]);
                $classification_id = $classification[$array[1]];
            }

            $model = new TechAchievements();

            for ($i = 0; $i < count($newData) - 1; $i++) {
                if (str_replace("\n", "", trim($newData[$i])) == "成果名称" || $newData[$i] == "成果名称") {
                    if (str_replace("\n", "", trim($newData[$i+1])) != "技术领域") {
                        $achievement_name = $newData[$i + 1];
                    }
                }

                if (str_replace("\n", "", trim($newData[$i])) == "技术领域") {
                    if (str_replace("\n", "", trim($newData[$i+1])) != "应用行业") {
                        // $classification_id = $classification[$newData[$i + 1]];
                        $technosphere = $newData[$i + 1];
                    }
                }

                if (str_replace("\n", "", trim($newData[$i])) == "技术成熟度") {
                    if (str_replace("\n", "", trim($newData[$i+1])) != "产业集群") {
                        $technology_maturity = $newData[$i + 1];
                    }

                    
                }

                if (str_replace(" ","",str_replace("\n", "", trim($newData[$i]))) == "成果内容介绍") {
                    $model->achievement_introduction = $newData[$i + 1];

                    // return str_replace("\n", "", trim($newData[$i]));
                }

                if (str_replace(" ","",str_replace("\n", "", trim($newData[$i]))) == "合作方式") {
                    if (str_replace("\n", "", trim($newData[$i+1])) != "联系人") {
                        $cooperation_mode = $newData[$i + 1];
                        $contacts_c = $newData[$i+3];
                    }
                }

                if (str_replace("\n", "", trim($newData[$i])) == "联系人") {
                    if (str_replace("\n", "", trim($newData[$i])) != "联系\n\n方式") {
                        $contacts = $newData[$i + 1];
                        $technology_source = $newData[$i + 1];
                    }
                }

                if (str_replace(" ","",str_replace("\n", "", trim($newData[$i]))) == "联系方式") {
                    if (str_replace("\n", "", trim($newData[$i+1])) != "单位") {
                        $phone = $newData[$i + 1];
                    }
                }

                if (str_replace(" ","",str_replace("\n", "", trim($newData[$i]))) == "单位" || str_replace("\n", "", trim($newData[$i])) == "单 位") {
                    $units_name = $newData[$i + 1];
                    // if($achievement_name == ""){
                    //     $achievement_name = $newData[$i + 5];
                    // }
                    break;
                }
            }

            if($contacts == ""){
                $contacts = $contacts_c;
                $technology_source = $contacts;
            }

            if($units_name == ""){
                $units_name == $newData[count($newData)-2];
            }

            $Tmodel = TechAchievements::where("achievement_name",$achievement_name)->find();

            if($Tmodel || $achievement_name == ""){
                continue;
            }


            $model->classification_id = $classification_id;
            $model->library_id = 6;
            $model->achievement_name = $achievement_name;
            $model->units_name = str_replace('\n\n', '', $units_name);
            $model->units_type = "科研究所";
            $model->contacts = $contacts;
            $model->email = "";
            $model->phone = $phone;
            $model->address = "广州市";
            $model->technology_source = $technology_source;
            $model->technosphere = $technosphere;
            $model->achievement_type = "新技术";
            $model->technology_maturity = $technology_maturity;
            $model->achievement_level = "未评价";
            $model->cooperation_mode = $cooperation_mode;
            $model->is_public = (int)1;
            $model->application_situation = "-";
            $model->application_condition = "-";
            $model->user_id = 0;
            $model->area_code = "";

            $model->save();

            $data = null;
            $columnCnt = 0;
            $options = [];
        }


        // return count($newData);
        return "完成！";
    }
}
